package com.ecar.api.service.pay.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.dom4j.DocumentException;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.pay.ali.AlipayConfig;
import com.ecar.api.pay.ali.sign.RSA;
import com.ecar.api.pay.wx.WeixinPay;
import com.ecar.api.pay.wx.WeixinPayConfig;
import com.ecar.api.rest.common.PublicController;
import com.ecar.api.service.pay.PayService;
import com.ecar.api.support.dto.Constants;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.UserUtil;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.api.support.util.WechatXMLParser;
import com.ecar.api.support.util.WilddogUtil;
import com.ecar.common.dto.DataBean;
import com.ecar.common.exception.MyException;
import com.ecar.common.util.JSONUtil;
import com.ecar.core.common.dao.CouponMapper;
import com.ecar.core.common.entity.Coupon;
import com.ecar.core.order.dao.OrderMapper;
import com.ecar.core.order.dao.OrderPaymentMapper;
import com.ecar.core.order.dao.PaymentMapper;
import com.ecar.core.order.entity.Order;
import com.ecar.core.order.entity.OrderPayment;
import com.ecar.core.order.entity.Payment;
import com.ecar.core.passenger.dao.PaymentCommentMapper;
import com.ecar.core.passenger.entity.PaymentComment;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.ecar.common.util.StringUtil;

/**
 * 
 */
@Service
@Transactional
public class PayServiceImpl implements PayService {

	private static Logger log = LoggerFactory.getLogger(PayServiceImpl.class);

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private PaymentMapper paymentMapper;

	@Autowired
	private OrderPaymentMapper orderPaymentMapper;

	@Autowired
	PaymentCommentMapper paymentCommentMapper;

	@Autowired
	CouponMapper couponMapper;

	@Override
	public DataBean setAlipaySign(String orderId, String couponActivityId) throws UnsupportedEncodingException {
		Order order = orderMapper.selectByOrderNum(orderId);
		// DataBean checked = checkOrderForPayment(order); //订单超时购票使用，预留方法
		// if (checked != null) return checked;

		String outTradeNo = order.getOrderNum();
		String subject = getOrderSubject(order);
		BigDecimal payPrice = new BigDecimal(0.00);
		if (couponActivityId != null && !couponActivityId.trim().equals("")) {// 前端传入优惠卷活动ID
			payPrice = new BigDecimal(order.getActualPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			payPrice = new BigDecimal(order.getOrderPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		}

		// BigDecimal payPrice = new BigDecimal(0.01).setScale(2,
		// BigDecimal.ROUND_HALF_UP);//测试
		StringBuilder paySign = new StringBuilder("");
		paySign.append("service=\"").append(AlipayConfig.payservice).append("\"");
		paySign.append("&partner=\"").append(AlipayConfig.partner).append("\"");
		paySign.append("&_input_charset=\"").append(AlipayConfig.input_charset).append("\"");
		paySign.append("&notify_url=\"").append(AlipayConfig.notify_url).append("\"");
		paySign.append("&out_trade_no=\"").append(outTradeNo).append("\"");
		paySign.append("&subject=\"").append(subject).append("\"");
		paySign.append("&payment_type=\"").append(AlipayConfig.payment_type).append("\"");
		paySign.append("&seller_id=\"").append(AlipayConfig.seller_id).append("\"");
		paySign.append("&total_fee=\"").append(payPrice.toString()).append("\"");
		paySign.append("&body=\"").append(subject).append("\"");
		// paySign.append("&it_b_pay=\"").append("30m").append("\"");//订单过期时间
		// 30分钟过期无效
		String signStr = RSA.sign(paySign.toString(), AlipayConfig.private_key, AlipayConfig.input_charset);
		signStr = URLEncoder.encode(signStr, "UTF-8");
		paySign.append("&sign=\"").append(signStr).append("\"");
		paySign.append("&sign_type=\"").append(AlipayConfig.sign_type).append("\"");
		log.info("支付宝支付：" + paySign.toString());

		// order.setOrderStatus(Order.ST.CREATED.val());
		// order.setOrderStatus(1);
		// orderMapper.updateByPrimaryKey(order);
		// subOrderDao.setSubOrderStatus(orderId, Order.ST.PAYING.val()); 预留方法
		return new DataBean(200, paySign.toString(), "支付宝签名返回成功");
	}

	private String getOrderSubject(Order order) {
		StringBuilder subject = new StringBuilder("网约车-购票");
		// int type = order.getType();
		// if (type == Order.TYPE_BOOKING) {
		// OrderDetailTicket detail = (OrderDetailTicket)
		// order.getOrderDetail();
		// subject.append(detail.getShiftNo()).append("*").append(detail.getTickets());
		// } else if (type == Order.TYPE_RENT) {
		// RtOrderDetail detail = (RtOrderDetail) order.getOrderDetail();
		// subject.append(detail.getStartCity()).append("-").append(detail.getTerminalCity())
		// .append("，").append(detail.getProduct().getDisplay());
		// } else if (type == Order.TYPE_BUS) {
		// BsOrderDetail detail = (BsOrderDetail) order.getOrderDetail();
		// subject.append(detail.getShiftNo()).append("*").append(detail.getTickets());
		// } else {
		// subject.append("湖北省公路客运订单");
		// }
		return subject.toString();
	}

	/**
	 * 支付前检查订单状态
	 *
	 * @param order
	 * @return
	 */
	private DataBean checkOrderForPayment(Order order) {
		if (order == null)
			return new DataBean(404, new JSONObject(), "没有找到指定的订单。");

		if (order.in(Order.ST.CREATED)) {
			if (isOrderTimeout(order)) {
				order.setOrderStatus(Order.ST.TIMEOUT.val());
				orderMapper.updateByOrderNumSelective(order);
				// subOrderDao.setSubOrderStatus(order.getId(),
				// Order.ST.TIMEOUT.val());
				return new DataBean(403, new JSONObject(), "订单已超时，无法支付!");
			}
		} else {
			if (order.eq(Order.ST.TIMEOUT))
				return new DataBean(403, new JSONObject(), "订单已超时，无法支付。");
			// return new DataBean(403,new JSONObject(), "订单状态不可支付。");
		}
		return null;
	}

	@Override
	public void checkPayment(String orderNum, String totalFee, String tradeNo,String dateStr,int payType) {
		log.info("==========================开始生成支付相关记录============================");
		log.info("订单号："+orderNum+",支付金额："+totalFee+",交易码："+tradeNo+",日期："+dateStr+",支付类型"+payType);
		SimpleDateFormat formatter; 
		if (payType == Constants.TYPE_ALIPAY){
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}else{
			formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		}
		Order order = orderMapper.selectByOrderNum(orderNum);
		if (order == null) return;
		Coupon coupon=couponMapper.selectByPrimaryKey(order.getCouponId());
		if (null!=coupon) {
			coupon.setStatus(Coupon.BEAN_USED);
			int as=couponMapper.updateByPrimaryKey(coupon);
			if(as<=0){
				log.info("更新优惠卷状态失败！");
			}
		}
		order.setPayStatus(Order.ST.PAID.val());//更新为已支付
		order.setActualPrice(Double.valueOf(totalFee));//实付金额
		orderMapper.updateByPrimaryKeySelective(order);
		BigDecimal payable = BigDecimal.valueOf(order.getOrderPrice()).movePointRight(2);
		BigDecimal paid = new BigDecimal(totalFee);
		if (payType == Constants.TYPE_ALIPAY) paid = paid.movePointRight(2);
//		 if (payable.intValue() != paid.intValue()) return;//测试时注释掉
		//删除野狗乘客数据
		WilddogUtil.removePassengerOrder(orderNum);
		OrderPayment orderPayment;
		try {
			Payment payment = paymentMapper.getByType(payType);
			orderPayment = orderPaymentMapper.getByOrderId(order.getId());
			if (orderPayment == null) {
				orderPayment = new OrderPayment();
				orderPayment.setId(UuidUtils.getUUID());
				orderPayment.setTradeNo(tradeNo);
				orderPayment.setOrderId(order.getId());
				orderPayment.setPaymentId(payment.getId());
				orderPayment.setPassengerId(order.getPassengerId());
				orderPayment.setCharge(order.getOrderPrice());
				orderPayment.setPay(order.getOrderPrice());
				orderPayment.setPayTime(formatter.parse(dateStr));
				orderPaymentMapper.insert(orderPayment);
				log.info("生成支付记录：" + JSONUtil.serialize(orderPayment));
			}
			PaymentComment paymentComment=paymentCommentMapper.selectByOrderNo(orderNum);
			if(paymentComment==null){
				paymentComment=new PaymentComment();
				paymentComment.setId(UuidUtils.getUUID());
				paymentComment.setUserId(String.valueOf(order.getPassengerId()));
				paymentComment.setDriverId(order.getDriverId());
				paymentComment.setOrderNo(order.getOrderNum());
				paymentComment.setPayablePrice(order.getOrderPrice());
				paymentComment.setPayStatus(Constants.PAY_SUCCESS);
				paymentComment.setCreateTime(new Date());
				paymentCommentMapper.insertSelective(paymentComment);
				log.info("生成评论记录：" + JSONUtil.serialize(paymentComment));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		boolean bNeedRefund = false;
		if (order.in(Order.ST.CREATED)) {
			
				try {
					log.info("支付成功，设置订单支付信息。");
					bNeedRefund = false;
					setOrderPaid(order, tradeNo, payType);
					log.info("订单已支付。");
				} catch (MyException e) {
					log.error(e.getMessage());
					log.info("设置订单支付信息失败，重新设置。");
					try {
						setOrderPaid(order, tradeNo, payType);
						log.info("订单已支付。");
					} catch (MyException e1) {
						e1.printStackTrace();
						log.info("设置订单支付信息失败，进行退款处理。。");
						bNeedRefund = true;
					}
				}
		}
		
	}

	/**
	 * 检查订单是否超时
	 *
	 * @param order
	 * @return
	 */
	private boolean isOrderTimeout(Order order) {
		int payLimit = Constants.PAY_TIME_OUT;

		// int type = order.getOrderType();
		// if (type == Order) {
		// payLimit = (String) ConfigStore.getValue(Configs.PAY_TIMEOUT);
		// if (StringUtil.isEmpty(payLimit)) return true;
		// } else if (type == Order.TYPE_RENT) {
		// payLimit = ConfigModuleStore.getValue(Configs.RT_TIMEOUT_PAY);
		// if (StringUtil.isEmpty(payLimit)) return true;
		// } else if (type == Order.TYPE_BUS) {
		// payLimit = ConfigModuleStore.getValue(Configs.BS_TIMEOUT_PAY);
		// if (StringUtil.isEmpty(payLimit)) return true;
		// } else {
		// return true;
		// }
		return order.isTimeout(payLimit);
		// return false;
	}

	/**
	 * 设置订单已支付
	 *
	 * @param order
	 * @param tradeNo
	 * @param payType
	 * @throws MyException
	 */
	private void setOrderPaid(Order order, String tradeNo, int payType) throws MyException {
		int type = order.getOrderType();
		int paid = Order.ST.PAID.val();
		order.setOrderStatus(paid);
		// order.setPaymentFlag(paid);
		orderMapper.updateByPrimaryKey(order);
	}

	@Override
	public DataBean setWxAppPaySign(String orderId, String ip, String couponActivityId)
			throws IOException, DocumentException {
		Order order = orderMapper.selectByOrderNum(orderId);
		// DataBean checked = checkOrderForPayment(order);//订单超时购票使用，预留方法
		// if (checked != null) return checked;

		String orderNum = order.getOrderNum();
		String body = getOrderSubject(order);

		// 将 订单金额转换成 以 分为单位，且不带小数点
		BigDecimal payPrice = new BigDecimal(0.00);
		if (couponActivityId != null && !couponActivityId.trim().equals("")) {// 前端传入优惠卷活动ID
			payPrice = new BigDecimal(order.getActualPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		} else {
			payPrice = new BigDecimal(order.getOrderPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		}
		// BigDecimal payPrice = new BigDecimal(0.01).setScale(2,
		// BigDecimal.ROUND_HALF_UP);//测试
		String ranStr = "" + WeixinPay.buildRandom(4);
		SortedMap<String, String> packageParams = new TreeMap<>();
		packageParams.put("appid", WeixinPayConfig.appid);
		packageParams.put("mch_id", WeixinPayConfig.mch_id);
		packageParams.put("nonce_str", ranStr);
		packageParams.put("body", body);
		packageParams.put("out_trade_no", orderNum);
		packageParams.put("total_fee", Integer.toString(payPrice.movePointRight(2).intValue()));
		packageParams.put("spbill_create_ip", ip);
		packageParams.put("notify_url", WeixinPayConfig.notify_url);
		packageParams.put("trade_type", "APP");
		packageParams.put("sign", WeixinPay.createSign(packageParams));

		// 发送请求
		String xmlStr = WechatXMLParser.map2XmlString(packageParams);
		Client c = null;
		ClientResponse response = null;
		String returnEntity = null;
		try {
			c = Client.create(new DefaultClientConfig());
			response = c.resource(WeixinPayConfig.unipay_url).entity(xmlStr).post(ClientResponse.class);
			returnEntity = response.getEntity(String.class);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "微信支付服务故障，请稍候重试！");
		} finally {
			if (response != null)
				response.close();
		}
		Map<String, String> returnMap = WechatXMLParser.parseString(returnEntity);
		String prepay_id;
		if ("SUCCESS".equals(returnMap.get("return_code")) && "SUCCESS".equals(returnMap.get("result_code"))) {
			prepay_id = returnMap.get("prepay_id");
		} else if ("FAIL".equals(returnMap.get("result_code"))
				&& "OUT_TRADE_NO_USED".equals(returnMap.get("err_code"))) {
			prepay_id = order.getPrepayId(); // 微信支付前需生成微信的预支付订单
		} else {
			log.info(returnMap.get("err_code_des"));
			return new DataBean(500, new JSONObject(), "统一支付接口获取预支付订单号出错。");
		}

		if (StringUtils.isEmpty(prepay_id)) {
			return new DataBean(500, new JSONObject(), "统一支付接口获取预支付订单号出错。");
		}

		// 预支付生成id之后
		SortedMap<String, String> returnPackageParams = new TreeMap<>();
		returnPackageParams.put("appid", WeixinPayConfig.appid);
		returnPackageParams.put("partnerid", WeixinPayConfig.mch_id);
		returnPackageParams.put("prepayid", prepay_id);
		returnPackageParams.put("package", "Sign=WXPay");
		returnPackageParams.put("noncestr", ranStr);
		returnPackageParams.put("timestamp", "" + WeixinPay.getUnixTime(new Date()));
		returnPackageParams.put("sign", WeixinPay.createSign(returnPackageParams));
		JSONObject returnjson = new JSONObject();
		returnjson.putAll(returnPackageParams);
		log.info("微信APP支付：" + returnjson);

		// order.setStatus(Order.ST.PAYING.val());
		// order.setOrderStatus(Order.ST.CREATED.val());
		order.setPrepayId(prepay_id);
		orderMapper.updateByPrimaryKey(order);
		// subOrderDao.setSubOrderStatus(orderId, Order.ST.PAYING.val());
		return new DataBean(200, returnjson, "微信签名成功");
	}

	@Override
	public DataBean setWxH5PaySign(String orderId, String loginToken) throws IOException, DocumentException {
		Order order = orderMapper.selectByOrderNum(orderId);
		// DataBean checked = checkOrderForPayment(order);
		// if (checked != null) return checked;
		String str = Redis.c.get(Redis.K.USER_PHONE.to(order.getPassengerPhone()));
		// User user=JSONUtil.deserialize(str, User.class);
		// String openid=user.getOpenid();
		String openid = UserUtil.getUser(order.getPassengerId(), loginToken).getOpenid();// 使用96513
																							// user表中微信授权
		// String openid="o1oYcs2CMtgQSmt8ElvExKRvy2dY";
		// String openid = order.getPassenger().getOpenid();
		if (StringUtil.isEmpty(openid))
			return new DataBean(401, "需要用户微信授权。");

		String token = WeixinPay.getAccessToken();
		if (StringUtils.isEmpty(token)) {
			log.debug("获取接口票据出错");
			return new DataBean(500, "获取预支付订单号出错。");
		}

		String body = getOrderSubject(order);

		// 将订单金额转换成以分为单位，且不带小数点
		// 将 订单金额转换成 以 分为单位，且不带小数点
		// BigDecimal payPrice =
		// BigDecimal.valueOf(order.getOrderPrice()).setScale(2,
		// BigDecimal.ROUND_HALF_UP);
		BigDecimal payPrice = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);// 测试

		JSONObject packageParams = new JSONObject();
		packageParams.put("openid", openid);
		packageParams.put("NOTIFY_URL", WeixinPayConfig.notify_h5_url);
		packageParams.put("total_fee", payPrice.movePointRight(2).intValue());
		packageParams.put("body", body);
		packageParams.put("out_trade_no", orderId);

		// 发送请求
		ClientResponse response = null;
		Client c = null;
		String returnEntity = null;
		try {
			c = Client.create(new DefaultClientConfig());
			response = c.resource(WeixinPayConfig.FWS_pay_url).queryParam("token", token)
					.entity(packageParams.toString()).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class);
			returnEntity = response.getEntity(String.class);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, "公众号支付服务故障，请稍候重试！");
		} finally {
			if (response != null)
				response.close();
			if (c != null)
				c.destroy();
		}
		log.debug("服务商接口返回：" + returnEntity);
		JSONObject retJson = JSONObject.fromObject(returnEntity);
		String resultCode = retJson.getString("resultCode");
		if ("0".equals(resultCode)) {
			JSONObject resultData = retJson.getJSONObject("resultData");
			log.info("微信H5支付：" + resultData.toString());
			String prepay_id = resultData.getString("package");
			prepay_id = prepay_id.split("=")[1];

			order.setPayStatus(Order.ST.CREATED.val());
			order.setPrepayId(prepay_id);
			orderMapper.updateByPrimaryKey(order);
			// subOrderDao.setSubOrderStatus(orderId, Order.ST.PAYING.val());
			// fire
			PublicController.sendF2FOrder(order);
			return new DataBean(200, resultData);
		} else {
			log.info(retJson.getString("resultMessage"));
			return new DataBean(500, "获取预支付订单号出错。");
		}
	}

	@Override
	public DataBean setNotWxH5PaySign(String orderNum, String ip, HttpServletResponse httpServletResponse)
			throws IOException, DocumentException {
		Order order = orderMapper.selectByOrderNum(orderNum);
		// DataBean checked = checkOrderForPayment(order);//订单超时购票使用，预留方法
		// if (checked != null) return checked;

		String body = getOrderSubject(order);

		// 将 订单金额转换成 以 分为单位，且不带小数点
		BigDecimal payPrice = new BigDecimal(0.00);
		// if(couponActivityId!=null &&
		// !couponActivityId.trim().equals("")){//前端传入优惠卷活动ID
		// payPrice = new BigDecimal(order.getActualPrice()).setScale(2,
		// BigDecimal.ROUND_HALF_UP);
		// }else{
		payPrice = new BigDecimal(order.getOrderPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
		// }
		// BigDecimal payPrice = new BigDecimal(0.01).setScale(2,
		// BigDecimal.ROUND_HALF_UP);//测试
		String ranStr = "" + WeixinPay.buildRandom(4);

		// 创建JSON对象
		JSONObject jsonObject = new JSONObject();

		// 创建用户实名信息JSON对象
		JSONObject sceneInfo = new JSONObject();
		// 组装json数组
		sceneInfo.put("type", "Wap");
		sceneInfo.put("app_name", "网约车");
		sceneInfo.put("package_name", "com.tencent.tmgp.sgame");
		jsonObject.put("scene_info", sceneInfo);

		SortedMap<String, String> packageParams = new TreeMap<>();
		packageParams.put("appid", WeixinPayConfig.appid);
		packageParams.put("mch_id", WeixinPayConfig.mch_id);
		packageParams.put("nonce_str", ranStr);
		packageParams.put("body", body);
		packageParams.put("out_trade_no", orderNum);
		packageParams.put("total_fee", Integer.toString(payPrice.movePointRight(2).intValue()));
		packageParams.put("spbill_create_ip", ip);
		packageParams.put("notify_url", WeixinPayConfig.notify_url);
		packageParams.put("trade_type", "MWEB");
		packageParams.put("scene_info", jsonObject.toString());
		packageParams.put("sign", WeixinPay.createSign(packageParams));

		// 发送请求
		String xmlStr = WechatXMLParser.map2XmlString(packageParams);
		Client c = null;
		ClientResponse response = null;
		String returnEntity = null;
		try {
			c = Client.create(new DefaultClientConfig());
			response = c.resource(WeixinPayConfig.unipay_url).entity(xmlStr).post(ClientResponse.class);
			returnEntity = response.getEntity(String.class);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "微信支付服务故障，请稍候重试！");
		} finally {
			if (response != null)
				response.close();
		}
		Map<String, String> returnMap = WechatXMLParser.parseString(returnEntity);
		String prepay_id;
		String mweb_url = null;
		if ("SUCCESS".equals(returnMap.get("return_code")) && "SUCCESS".equals(returnMap.get("result_code"))) {
			prepay_id = returnMap.get("prepay_id");
			mweb_url = returnMap.get("returnMap");
		} else if ("FAIL".equals(returnMap.get("result_code"))
				&& "OUT_TRADE_NO_USED".equals(returnMap.get("err_code"))) {
			prepay_id = order.getPrepayId(); // 微信支付前需生成微信的预支付订单
			log.info(returnMap.get("商户订单号重复,同一笔交易不能多次提交。"));
		} else {
			log.info(returnMap.get("err_code_des"));
			return new DataBean(500, new JSONObject(), "统一支付接口获取预支付订单号出错。");
		}

		if (StringUtils.isEmpty(prepay_id) && StringUtils.isEmpty(mweb_url)) {
			return new DataBean(500, new JSONObject(), "统一支付接口获取预支付订单号出错。");
		}
		log.info("prepay_id:" + prepay_id + " mweb_url:" + mweb_url);
		try {
			httpServletResponse.sendRedirect(mweb_url);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 预支付生成id之后
		SortedMap<String, String> returnPackageParams = new TreeMap<>();
		returnPackageParams.put("appid", WeixinPayConfig.appid);
		returnPackageParams.put("partnerid", WeixinPayConfig.mch_id);
		returnPackageParams.put("prepayid", prepay_id);
		returnPackageParams.put("package", "Sign=WXPay");
		returnPackageParams.put("noncestr", ranStr);
		returnPackageParams.put("timestamp", "" + WeixinPay.getUnixTime(new Date()));
		returnPackageParams.put("sign", WeixinPay.createSign(returnPackageParams));
		JSONObject returnjson = new JSONObject();
		returnjson.putAll(returnPackageParams);
		log.info("微信APP支付：" + returnjson);

		// order.setStatus(Order.ST.PAYING.val());
		// order.setOrderStatus(Order.ST.CREATED.val());
		order.setPrepayId(prepay_id);
		orderMapper.updateByPrimaryKey(order);
		// subOrderDao.setSubOrderStatus(orderId, Order.ST.PAYING.val());
		return new DataBean(200, returnjson, "微信签名成功");
	}

	@Override
	public void createPayment(String orderNum, int totalFee, String tradeNo, String dateStr, int payType) {
		log.info("==========================开始生成支付相关记录============================");
		log.info("订单号：" + orderNum + ",支付金额：" + totalFee + ",交易码：" + tradeNo + ",日期：" + dateStr + ",支付类型" + payType);
		SimpleDateFormat formatter;
		if (payType == Constants.TYPE_ALIPAY) {
			formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		} else {
			formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		}
		Order order = orderMapper.selectByOrderNum(orderNum);
		if (order == null)
			return;

		/*
		 * Coupon coupon=couponMapper.selectByPrimaryKey(order.getCouponId());
		 * coupon.setStatus(Coupon.BEAN_USED); int
		 * as=couponMapper.updateByPrimaryKey(coupon); if(as<=0){
		 * log.info("更新优惠卷状态失败！"); }
		 */
		order.setPayStatus(Order.ST.PAID.val());// 更新为已支付
		order.setActualPrice(Double.valueOf(totalFee));// 实付金额
		orderMapper.updateByPrimaryKeySelective(order);
		BigDecimal payable = BigDecimal.valueOf(order.getOrderPrice()).movePointRight(2);
		BigDecimal paid = new BigDecimal(totalFee);
		if (payType == Constants.TYPE_ALIPAY)
			paid = paid.movePointRight(2);
		// if (payable.intValue() != paid.intValue()) return;//测试时注释掉
		// 删除野狗乘客数据
		WilddogUtil.removePassengerOrder(orderNum);
		OrderPayment orderPayment;
		try {
			Payment payment = paymentMapper.getByType(payType);
			orderPayment = orderPaymentMapper.getByOrderId(order.getId());
			if (orderPayment == null) {
				orderPayment = new OrderPayment();
				orderPayment.setId(UuidUtils.getUUID());
				orderPayment.setTradeNo(tradeNo);
				orderPayment.setOrderId(order.getId());
				orderPayment.setPaymentId(payment.getId());
				orderPayment.setPassengerId(order.getPassengerId());
				orderPayment.setCharge(order.getOrderPrice());
				orderPayment.setPay(order.getOrderPrice());
				orderPayment.setPayTime(formatter.parse(dateStr));
				orderPaymentMapper.insert(orderPayment);
				log.info("生成支付记录：" + JSONUtil.serialize(orderPayment));
			}
			PaymentComment paymentComment = paymentCommentMapper.selectByOrderNo(orderNum);
			if (paymentComment == null) {
				paymentComment = new PaymentComment();
				paymentComment.setId(UuidUtils.getUUID());
				paymentComment.setUserId(String.valueOf(order.getPassengerId()));
				paymentComment.setDriverId(order.getDriverId());
				paymentComment.setOrderNo(order.getOrderNum());
				paymentComment.setPayablePrice(order.getOrderPrice());
				paymentComment.setPayStatus(Constants.PAY_SUCCESS);
				paymentComment.setCreateTime(new Date());
				paymentCommentMapper.insertSelective(paymentComment);
				log.info("生成评论记录：" + JSONUtil.serialize(paymentComment));
			}

		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		boolean bNeedRefund = false;
		if (order.in(Order.ST.CREATED)) {

			try {
				log.info("支付成功，设置订单支付信息。");
				bNeedRefund = false;
				setOrderPaid(order, tradeNo, payType);
				log.info("订单已支付。");
			} catch (MyException e) {
				log.error(e.getMessage());
				log.info("设置订单支付信息失败，重新设置。");
				try {
					setOrderPaid(order, tradeNo, payType);
					log.info("订单已支付。");
				} catch (MyException e1) {
					e1.printStackTrace();
					log.info("设置订单支付信息失败，进行退款处理。。");
					bNeedRefund = true;
				}
			}
		}

	}

}
